<script lang="ts" setup>
import { ref, onBeforeMount } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { loginParams, registerParams } from './login.types'
import { userLogin, userRegister, userTokenValidate } from '@/apis/user'
import { useUserStore } from '@/stores/useUserStore'
import router from '@/router/index'

defineOptions({
  name: 'login',
})
const user = ref<loginParams>({
  username: '',
  password: '',
})
const loginFormRef = ref<FormInstance>()
const loginRules = ref<FormRules<typeof user>>({
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 3, max: 6, message: '账号长度为3-6位', trigger: 'blur' },
    {
      // 账号只能包含英文大小写字母和数字
      pattern: /^[A-Za-z0-9]+$/,
      message: '只能只能包含英文大小写字母和数字',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      min: 3,
      max: 10,
      message: '密码长度为3-10位',
      trigger: 'blur',
    },
    {
      pattern: /^[A-Za-z0-9]+$/,
      message: '密码只能包含英文大小写字母和数字',
      trigger: 'blur',
    },
  ],
})

const userStore = useUserStore()

const handleLogin = () => {
  userLogin(user.value)
    .then(res => {
      const result = res.data
      if (result.success) {
        let params = {
          // 读取服务器传过来的用户信息
          ...result.data,
        }
        userStore.setUserInfo(params)
        router.push('/pyEditor')
        ElMessage.success(result.message)
      } else {
        ElMessage.error(result.message)
      }
    })
    .catch(err => {
      ElMessage.error('未知错误')
      console.log(err)
    })
}

const isRegister = ref(false)
const registerFormRef = ref<FormInstance>()

const userRegisterInfo = ref<registerParams>({
  nickname: '',
  username: '',
  password: '',
})
const registerRules = ref<FormRules<typeof userRegisterInfo>>({
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 3, max: 6, message: '账号长度为3-6位', trigger: 'blur' },
    {
      // 账号只能包含英文大小写字母和数字
      pattern: /^[A-Za-z0-9]+$/,
      message: '只能包含英文大小写字母和数字',
      trigger: 'blur',
    },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    {
      min: 3,
      max: 10,
      message: '密码长度为3-10位',
      trigger: 'blur',
    },
    {
      // 密码只能包含英文大小写字母和数字
      pattern: /^[A-Za-z0-9]+$/,
      message: '密码只能包含英文大小写字母和数字',
      trigger: 'blur',
    },
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' },
    { min: 1, max: 10, message: '昵称长度为1-10位', trigger: 'blur' },
  ],
})

const toggleRegister = () => {
  isRegister.value = !isRegister.value
}

const handleRegister = () => {
  userRegister(userRegisterInfo.value)
    .then(res => {
      const result = res.data
      if (result.success) {
        ElMessage.success(result.message)
      } else {
        ElMessage.error(result.message)
      }
    })
    .catch(err => {
      console.log(err)
      ElMessage.error('未知错误')
    })
}

const submitForm = async (
  formEl: FormInstance | undefined,
  callback: Function | undefined
) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      callback?.()
    } else {
      console.log('error submit!', fields)
    }
  })
}

onBeforeMount(() => {
  // localStorage.getItem('user') && router.push('/pyEditor')
  // 验证Token是否有效
  const token = JSON.parse(localStorage.getItem('user') || '{}').token
  if (token) {
    userTokenValidate({ token: token })
      .then(res => {
        if (res.data.success) {
          router.push('/pyEditor')
        } else {
          ElMessage.error(res.data.message)
        }
      })
      .catch(() => {
        ElMessage.error('未知错误')
      })
  }
})
</script>

<template>
  <section class="login-page">
    <main class="welcome-pic">
      <img src="@/assets/images/undraw_welcome_cats_thqn.png" alt="" />
    </main>
    <section class="form-container">
      <!-- 注册用表单 -->
      <main
        class="login-page-form-register"
        :class="{ 'is-register': isRegister }"
      >
        <div class="login-page-title">注册</div>
        <div class="login-page-form-container">
          <el-form
            :model="userRegisterInfo"
            :rules="registerRules"
            ref="registerFormRef"
          >
            <el-form-item prop="nickname">
              <el-input
                v-model="userRegisterInfo.nickname"
                placeholder="请输入昵称"
                prefix-icon="Avatar"
              ></el-input>
            </el-form-item>
            <el-form-item prop="username">
              <el-input
                v-model="userRegisterInfo.username"
                placeholder="请输入账号"
                prefix-icon="User"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                prop="password"
                v-model="userRegisterInfo.password"
                type="password"
                placeholder="请输入密码"
                show-password
                prefix-icon="Lock"
              ></el-input>
            </el-form-item>
            <el-button
              color="#c5a47a"
              @click="submitForm(registerFormRef, handleRegister)"
              >注册!</el-button
            >
          </el-form>
        </div>
        <div class="login-page-footer">
          <el-text type="info" @click="toggleRegister">返回登录</el-text>
        </div>
      </main>
      <!-- 登陆用表单 -->
      <main class="login-page-form" :class="{ 'is-register': isRegister }">
        <div class="login-page-title">登录</div>
        <div class="login-page-subtitle">
          <el-text type="info">登录以开始编程之旅</el-text>
        </div>
        <div class="login-page-form-container">
          <el-form :model="user" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="id">
              <el-input
                v-model="user.username"
                placeholder="请输入账号"
                prefix-icon="User"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                prop="password"
                v-model="user.password"
                type="password"
                placeholder="请输入密码"
                show-password
                prefix-icon="Lock"
              ></el-input>
            </el-form-item>
            <el-button
              color="#c5a47a"
              @click="submitForm(loginFormRef, handleLogin)"
              >登录!</el-button
            >
          </el-form>
        </div>
        <div class="login-page-footer">
          <el-text type="info" @click="toggleRegister"
            >没有账号?立即注册</el-text
          >
        </div>
      </main>
    </section>
  </section>
</template>

<style lang="scss" scoped>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  background-color: var(--gray-color);
  .welcome-pic {
    width: 800px;
    height: 800px;
    animation: rotate 1s ease infinite;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .form-container {
    position: relative;
    width: 450px;
    overflow: hidden;
    border: 1px solid var(--primary-color);
    border-radius: 25px;
    // z-index: 10;
    .login-page-form,
    .login-page-form-register {
      width: 100%;
      height: 350px;
      padding: 30px;
      background-color: #fff;
      display: flex;
      justify-content: center;
      flex-direction: column;
      transition: all 0.5s;
      .login-page-title {
        color: #3f3d56;
        font-size: 30px;
        font-weight: 700;
        margin-bottom: 5px;
      }
      .login-page-subtitle {
        color: lighten(#3f3d56, 5%);
        margin-bottom: 15px;
      }
      .login-page-form-container {
        width: 100%;
      }
    }
    .login-page-form-register {
      position: absolute;
      transition: all 0.5s;
      transform: translateX(100%);
    }
    .login-page-form-register.is-register {
      transform: translateX(0);
    }
    .login-page-form.is-register {
      transform: translateX(-100%);
    }
    &:deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 1px var(--primary-color) inset;
    }
    &:deep(.el-button) {
      width: 100%;
      color: #fff;
      // border-radius: 10px;
    }
    .login-page-footer {
      display: flex;
      justify-content: center;
      margin-top: 15px;
      &:deep(.el-text) {
        animation: rotate 1s ease infinite;
        &:hover {
          cursor: pointer;
          color: var(--primary-color);
        }
      }
    }
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0);
  }

  20% {
    transform: rotate(-2deg);
  }

  60% {
    transform: rotate(0);
  }

  80% {
    transform: rotate(2deg);
  }

  100% {
    transform: rotate(0);
  }
}
</style>
